package com.example.whatrubbish.controller;

import com.example.whatrubbish.model.ReceiverAddress;
import com.example.whatrubbish.service.ReceiverAddressService;
import com.example.whatrubbish.utils.Constants;
import com.example.whatrubbish.utils.DemoException;
import com.example.whatrubbish.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/receiverAddress")
public class ReceiverAddressController {
    @Autowired
    ReceiverAddressService receiverAddressService;

    @GetMapping("")
    public JsonResult getByUser(@RequestParam(value = "userId", required = false) String userId) {
        return new JsonResult(Constants.STATUS_SUCCESS, "success", receiverAddressService.getByUserId(userId));
    }

    @PostMapping("")
    public JsonResult insert(@RequestBody @Validated ReceiverAddress receiverAddress) {
        try {
            receiverAddressService.insertSelective(receiverAddress);
        } catch (Exception e) {
            if (e instanceof DemoException) {
                return new JsonResult(Constants.STATUS_FAIL, e.getMessage());
            }
            return new JsonResult(Constants.STATUS_FAIL, "添加失败");
        }
        return new JsonResult(Constants.STATUS_SUCCESS, "success");
    }

    @PutMapping("")
    public JsonResult update(@RequestBody @Validated ReceiverAddress receiverAddress) {
        try {
            receiverAddressService.updateByPrimaryKeySelective(receiverAddress);
        } catch (Exception e) {
            return new JsonResult(Constants.STATUS_FAIL, "修改失败");
        }
        return new JsonResult(Constants.STATUS_SUCCESS, "success");
    }

    @DeleteMapping("")
    public JsonResult delete(@RequestBody ReceiverAddress address) {
        try {
            receiverAddressService.deleteByPrimaryKey(address.getId());
        } catch (Exception e) {
            return new JsonResult(Constants.STATUS_FAIL, "删除失败");
        }
        return new JsonResult(Constants.STATUS_SUCCESS, "success");
    }
}
